import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// create an axios instance
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_IPS, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
request.interceptors.request.use(config => {
  // 在这个位置需要统一的去注入token
  if (store.getters.token) {
    // 如果token存在 注入token
    if (Date.now() - localStorage.getItem('time') > 1000 * 60 * 60 * 2) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject('登录超时(主动)')
    }
  }
  // 无论如何都要返回放行
  return config // 必须返回配置
})

// response interceptor
request.interceptors.response.use(respone => {
  const { msg, data } = respone.data
  if (msg) {
    return data
  } else {
    Message.error(msg)
    return Promise.reject(new Error(msg))
  }
}, error => {
  Message.error(error.msg)
  return Promise.reject(error)
})

export default request
